<template>
	<view>
		<u-toast ref="uToast" />
		<common :tips='commonTips'></common>
		<u-mask z-index="1000" :custom-style="{background: 'rgba(0, 0, 0, 0.1)'}" :show="maskShow"
			@click="maskClick"></u-mask>
		<u-action-sheet :list="sessionLongpressList" @click="sessionLongpressAction"
			v-model="sessionLongpressShow"></u-action-sheet>
		<!-- 顶部搜索栏-start -->
		<view class="search">
			<view class="search-box">
				<u-search @search="search()" @custom="search()" v-model="keywords" class="search-box-u-search"
					shape="square" placeholder="搜索其实很简单" :clearabled="true" :show-action="false"></u-search>
				<view @click="toggleMessageMenu" class="message-menu">
					<u-icon class="message-menu-icon" name="plus" :class="messageMenu.show ? 'im-bg-grey':''"
						color="#3f3f3f" size="40"></u-icon>
					<view v-if="messageMenu.show" :style="{top: messageMenu.top, left: messageMenu.left}"
						class="message-menu-box popup-menu">
						<navigator class="popup-menu-item" url="/pages/search/new-contact" open-type="navigate">加好友/群
						</navigator>
						<navigator url="/pages/pick-user/pick-user?action=create-group" open-type="navigate">
							<view class="popup-menu-item">创建群聊</view>
						</navigator>
					</view>
				</view>
			</view>
		</view>
		<!-- 顶部搜索栏-end -->
		<!-- 待办-start -->
		<u-cell-group class="to-do" :border="false">
			<navigator url="/pages/center/to-do" open-type="navigate">
				<u-cell-item class="to-do-cell-item" :border-bottom="false" :arrow="true" :title="'待办 • ' + TODOcount">
					<u-icon class="to-do-cell-item-icon" slot="icon" size="32" name="/static/icon/to-do.png"></u-icon>
				</u-cell-item>
			</navigator>
		</u-cell-group>
		<!-- 待办-end -->
		<u-line length="92%" class="session-list-top-line" color="#F2F3F4" />
		<!-- 会话列表-start -->
		<view class="session-list">
			<block v-for="(item, index) in sessionListTop" :key="item.id">
				<session @click.native="goToSessionInfo(item.id, item.type, item.chat_id,item)"
					@longpress.native="sessionLongpress(item.id, item.top)" :item="item"></session>
			</block>
			<block v-for="(item, index) in sessionList" :key="item.id">
				<session @click.native="goToSessionInfo(item.id, item.type, item.chat_id,item)"
					@longpress.native="sessionLongpress(item.id, item.top)" :item="item"></session>
			</block>
			<view class="im-data-none" v-if="loadStatus">{{loadStatus}}</view>
		</view>
		<!-- 会话列表-end -->
	</view>
</template>

<script>
	import appDialog from '../../node_modules/js_sdk/dialog';
	import Config from "@/common/config.js"; // 本地配置数据
	import {
		genTestUserSig
	} from '../../debug/GenerateTestUserSig.js';
	export default {
		data() {
			return {
				keywords: '',
				maskShow: false,
				messageMenu: {
					show: false
				},
				sessionList: [],
				sessionListTop: [],
				TODOcount: 0,
				pageDataLoadBool: false,
				sessionLongpressList: [],
				sessionLongpressShow: false,
				loadStatus: '加载中...',
				commonTips: ''
			}
		},
		onLoad: function() {
			this.ws.pageFun(this.pageDataLoad, this);
			// #ifndef H5
			const userinfo = uni.getStorageSync("userinfo");
			this.loginTUICallKit(userinfo.id);
			this.checkForUpdate() // 检查版本更新
			// #endif
			// this.checkForUpdate() // 检查版本更新
			
			this.checUpdateLogin() // 检查是否需要更新登录时间
			// this.onPullDownRefresh(); // 页面每次显示时自动刷新
		},
		onShow: function() {
			// 每次进入页面自动刷新会话列表
			this.handleRefresh();
			// this.ws.pageFun(() => this.pageDataLoad(true), this);
			// this.pageDataLoad();

			// 检查 domain 区域是否变更
			this.checkZoneDomain();
			var that = this
			if (this.ws.pageRefresh.message) {
				// 被其他页面通知刷新会话列表(更新列表中的好友备注等)
				this.ws.pageFun(this.pageDataLoad, this);
				this.ws.clearPageRefresh()
				this.ws.pageRefresh.message = false
				this.ws.pageRefresh.sessionInfo = false
				this.ws.messageShow = [] // 已经重载,无需执行messageShow中的方法
				return;
			}
			if (this.ws.messageShow.length) {
				for (let m in this.ws.messageShow) {
					if (typeof this.ws.messageShow[m] == 'function') {
						this.ws.messageShow[m](that)
						this.ws.messageShow[m] = null
					}
				}
			}
			if (!this.pageDataLoadBool) {
				return;
			}
			that.ws.checkNetwork(that)
			that.ws.pageFun(function() {
				that.ws.send({
					c: 'ImBase',
					a: 'loadTODO',
					data: {
						'method': 'get-all-count'
					}
				})
			}, that);


		},
		onPullDownRefresh() {
			this.pageDataLoadBool = true;
			this.ws.pageFun(() => this.pageDataLoad(true), this);
			this.ws.onMessageCallBack.set('load_session_list', (msg) => {
				if (msg.data.data.refresh && msg.data.data.method == 'load') {
					this.$refs.uToast.show({
						title: '刷新成功~',
						type: 'success'
					})
					uni.stopPullDownRefresh()
				}
			})
		},
		methods: {
			checUpdateLogin() {
				console.log("更新登录时间")
				
				const userinfo = uni.getStorageSync('userinfo');
				console.log(userinfo.logintime)
				if (!userinfo || !userinfo.logintime) return;
			
				const lastLoginTime = parseInt(userinfo.logintime);
				// const lastLoginTime = 1745415126;
				const now = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
				console.log(now)
				// 超过半小时（900秒）就更新
				if (now - lastLoginTime >= 900) {
					// console.log("登录时间超过半小时，准备更新");
			
					this.$u.post(`https://${Config.baseUrl}/api/auto/updateLoginTime`, {
						user_id: userinfo.id
					}).then(res => {
						if (res.code === 1) {
							// console.log("登录时间已更新");
			
							// 更新本地 userinfo 的 logintime
							userinfo.logintime = now;
							uni.setStorageSync('userinfo', userinfo);
						} else {
							console.warn("更新登录时间失败", res.msg);
						}
					}).catch(err => {
						console.error("请求更新登录时间接口失败", err);
					});
				}
			},
			checkForUpdate() {
				const that = this;
				console.log("检查版本更新")
				console.log("url:", Config.baseUrl);
				
				// 获取当前版本号是异步的
				that.getCurrentVersionCode().then(currentVersionCode => {
					console.log("当前版本号:", currentVersionCode); 
					

					that.$u.get(`/api/Redpacket/getLatestAppVersion`)
						.then(res => {
							if (res.status === 'success' && res.data) {
								const latestVersion = res.data;

								// 假设 version 是字符串如 "2.0.0"，可以用某种方式转成整数版本号，也可以让后端返回 version_code
								const latestVersionCode = parseInt(latestVersion.version.replace(/\D/g, '')) ||
									0;
								console.log("服务端返回版本号:", latestVersionCode);

								if (latestVersionCode > currentVersionCode) {
									// 根据 force_update 字段决定是否允许取消按钮
									const isForceUpdate = latestVersion.force_update === 1;
									appDialog.show(latestVersion.download_url, latestVersion.update_message, isForceUpdate);
								} else {
									// uni.showToast({
									// 	title: '当前已是最新版',
									// 	icon: 'none'
									// });
								}
							} else {
								// uni.showToast({
								// 	title: '版本检查失败',
								// 	icon: 'none'
								// });
							}
						})
						.catch(err => {
							console.error('版本检查请求失败：', err);
							// uni.showToast({
							// 	title: '请求失败，请稍后重试',
							// 	icon: 'none'
							// });
						});
				});
			},

			getCurrentVersionCode() {
				return new Promise((resolve) => {
					plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
						resolve(parseInt(wgtinfo.versionCode));
					});
				});
			},

			checkZoneDomain() {
				const selectedZoneDomain = uni.getStorageSync('selectedZoneDomain');
				const userinfo = uni.getStorageSync('userinfo');

				if (selectedZoneDomain) {
					// 如果没有设置服务分区，或已设置但不同
					if (!userinfo.service_domain || userinfo.service_domain !== selectedZoneDomain) {
						console.log('服务分区不同，准备更新...');

						this.updateServiceDomain(userinfo.id, selectedZoneDomain);

						// 更新本地 userinfo 的值
						userinfo.service_domain = selectedZoneDomain;
						uni.setStorageSync('userinfo', userinfo);
					}
				}
			},
			updateServiceDomain: function(userId, serviceDomain) {
				var that = this;

				that.$u.post(`https://${Config.baseUrl}/api/Redpacket/updateServiceDomain`, {
					id: userId,
					service_domain: serviceDomain
				}).then(res => {
					if (res.status === 'success') {
						console.log('服务分区更新成功');
					} else {
						uni.showToast({
							title: res.message || '服务分区更新失败'
						});
					}
				}).catch(err => {
					console.error('服务分区请求失败：', err);
					uni.showToast({
						title: '请求失败，请重试！'
					});
				});
			},
			// 真正的刷新逻辑放这里
			handleRefresh() {
				this.pageDataLoad(true);
			},
			loginTUICallKit(userID) {
				console.log("hhhssd")
				userID = userID.toString();
				const userSig = genTestUserSig(userID).userSig;
				const SDKAppID = genTestUserSig('').sdkAppID;
				console.log("当前登录的id", userID);
				if (!SDKAppID) {
					console.error('请检查 uni-app/debug/GenerateTestUserSig.js 文件的 sdkAppID、usersig 是否填写');
				} else if (typeof SDKAppID !== 'number') {
					console.error('请检查 uni-app/debug/GenerateTestUserSig.js 文件下的 sdkAppID 是否为数字number 类型');
				}
				uni.$TUIKit.login({
					userID: userID,
					userSig: userSig
				});
				uni.$TUICallKit.login({
					SDKAppID,
					userID: userID,
					userSig: userSig,
				}, (res) => {
					console.log("res", res);
					if (res.code === 0) {
						// 开启悬浮窗
						uni.$TUICallKit.enableFloatWindow(true);
					} else {
						console.error('login failed, failed message = ', res.msg);
					}

				});
				getApp().globalData.userID = userID;
				getApp().globalData.userSig = userSig;
			},
			pageDataLoad: function(refresh = false) {
				console.log("hhhhsdfsfdsfsfdsfsdfsfsdfsdfsdfsd")

				this.pageDataLoadBool = true
				this.ws.send({
					c: 'User',
					a: 'loadSessionList',
					data: {
						'refresh': refresh
					}
				})
				this.ws.send({
					c: 'ImBase',
					a: 'loadTODO',
					data: {
						'method': 'get-all-count'
					}
				})
			},
			goToSessionInfo: function(id, type, chat_id, item) {
				const userinfo = uni.getStorageSync('userinfo');
				console.log("item:" + item);
				console.log("id:" + id);
				console.log(JSON.stringify(item, null, 2));
				const callId = item.user_two == userinfo.id ? item.user_one : item.user_two;
				if (callId) {
					uni.setStorageSync('recipient_id', callId.toString());
				}
				if (callId == item.user_one) {
					uni.setStorageSync('sender_id', item.user_two);
				} else {
					uni.setStorageSync('sender_id', item.user_one);
				}

				console.log("item111111111111", item);
				console.log("userinfo", userinfo);
				var url = '/pages/session-info/session-info?id=' + id
				if (type == 'service') {
					if (chat_id != 3) {
						url = '/pages/session-info/notice-session-info?session_id=' + id
					}
				}
				uni.navigateTo({
					url: url
				})
			},
			sessionLongpress: function(id, top) {
				this.sessionLongpressShow = true
				this.sessionLongpressList = [{
					text: top ? '取消置顶' : '置顶',
					id: id
				}, {
					text: '移除会话',
					color: '#f74c31',
					id: id
				}]
			},
			sessionLongpressAction: function(idx) {
				var that = this
				if (idx == 0) {
					that.ws.pageFun(function() {
						that.ws.send({
							c: 'User',
							a: 'sessionOperation',
							data: {
								id: that.sessionLongpressList[idx].id,
								action: 'session-top',
								source: 'uni-app'
							}
						})
					}, that)
				} else if (idx == 1) {
					that.ws.pageFun(function() {
						that.ws.send({
							c: 'User',
							a: 'sessionOperation',
							data: {
								action: "session-remove",
								id: that.sessionLongpressList[idx].id,
								source: 'uni-app'
							}
						});
					}, that)
				}
			},
			maskClick: function() {
				this.messageMenu.show && this.toggleMessageMenu()
			},
			toggleMessageMenu: function(e) {
				var that = this
				if (that.messageMenu.show) {
					that.maskShow = false
					that.messageMenu.show = false
					return;
				}
				that.messageMenu = {
					show: true,
					top: (e.detail.y + 14) + 'px',
					left: (e.detail.x - 120) + 'px'
				}
				that.maskShow = true
			},
			search: function() {
				if (!this.keywords) {
					this.$refs.uToast.show({
						title: '请输入关键词~',
						type: 'error'
					})
					return;
				}
				uni.navigateTo({
					url: '/pages/search/search?keywords=' + this.keywords,
					success: () => {
						this.keywords = ''
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #FFFFFF;
	}

	.search {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.search-box {
		display: flex;
		align-items: center;
		padding: 20rpx 0 10rpx 0;
	}

	.search-box .search-box-u-search {
		width: 616rpx;
	}

	.search-box .message-menu {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 20rpx;
	}

	.message-menu .message-menu-icon {
		padding: 6rpx;
		z-index: 1001;
		border-radius: 4px;
	}

	.message-menu-box {
		position: absolute;
		background: #FFFFFF;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, .1);
		border-radius: 4px;
		z-index: 1001;
	}

	.popup-menu .popup-menu-item {
		padding: 30rpx 70rpx;
		text-align: center;
		border-bottom: 1px solid #F3F4F6;
	}

	.popup-menu .popup-menu-item:last-child {
		border: none;
	}

	.to-do .to-do-cell-item .to-do-cell-item-icon {
		margin-right: 10rpx;
	}

	.session-list-top-line {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.im-bg-grey {
		background-color: $--grey;
		color: $--white;
	}
</style>